package com.gzgy.ustore.api.service.impl;

import com.gzgy.ustore.api.common.exception.BaseAPIException;
import com.gzgy.ustore.api.common.exception.ExceptionCodeStatusEnum;
import com.gzgy.ustore.api.common.util.DateUtil;
import com.gzgy.ustore.api.common.util.I18nUtil;
import com.gzgy.ustore.api.dao.ApkFileRecordDao;
import com.gzgy.ustore.api.dao.AppDownloadRuleDao;
import com.gzgy.ustore.api.dao.AppInfoDao;
import com.gzgy.ustore.api.dao.PdaMgrDao;
import com.gzgy.ustore.api.model.ApkInfo;
import com.gzgy.ustore.api.model.ApkListModel;
import com.gzgy.ustore.api.service.ApkService;
import com.ustore.model.ApkFileRecord;
import com.ustore.model.AppDownloadRule;
import com.ustore.model.AppInfo;
import com.ustore.model.PdaMgr;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yimi on 2017/7/3.
 */
@Service
public class ApkServiceImpl implements ApkService {

    private Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private ApkFileRecordDao apkFileRecordDao;

    @Autowired
    private AppInfoDao appInfoDao;

    @Autowired
    private AppDownloadRuleDao appDownloadRuleDao;

    @Autowired
    private PdaMgrDao pdaMgrDao;

    @Override
    public List<ApkListModel> getApkList(String sn, String timeStamp) {

        //检测 时间是否有效
        checkTimeStamp(timeStamp);

        PdaMgr mgr = pdaMgrDao.getPdaMgrInfoBySn(sn);
        if(mgr == null){
            int errorCode = ExceptionCodeStatusEnum.DVC_NOT_FOUND_EXCEPTION.toInt();
            String errorMsg = I18nUtil.getMessage(errorCode,null,"zh_CN");
            throw new BaseAPIException(errorMsg,errorCode);
        }
        List<ApkListModel> apkListModelList = appInfoDao.getApkForAppDvc();
        return apkListModelList;
    }

    @Override
    public String checkForRegister(String sn, String timeStamp) {
        //检测 时间是否有效
        checkTimeStamp(timeStamp);

        PdaMgr mgr = pdaMgrDao.getPdaMgrInfoBySn(sn);
        return mgr==null?"0":"1";
    }

    @Override
    public String registerDeviceToken(String sn, String timeStamp, String deviceToken) throws SQLException {
        //检测 时间是否有效
        checkTimeStamp(timeStamp);
        PdaMgr mgr = pdaMgrDao.getPdaMgrInfoBySn(sn);
        if(mgr == null){
            int errorCode = ExceptionCodeStatusEnum.DVC_NOT_FOUND_EXCEPTION.toInt();
            String errorMsg = I18nUtil.getMessage(errorCode,null,"zh_CN");
            throw new BaseAPIException(errorMsg,errorCode);
        }
        mgr.setDvcToken(deviceToken);
        pdaMgrDao.update(mgr);

        return "注册成功";
    }

    @Override
    @Transactional
    public ApkFileRecord apkUpload(String apkPath, String imagePath, Double appSize, ApkInfo apkInfo, String userId, String companyId, String appCode) {

        //add apk file record
        ApkFileRecord apkFileRecord = new ApkFileRecord();
        apkFileRecord.setAppSize(appSize);
        apkFileRecord.setAppLogoPath(imagePath);
        apkFileRecord.setAppName(apkInfo.getApplicationLable());
        apkFileRecord.setAppPath(apkPath);
        apkFileRecord.setAppPackageName(apkInfo.getPackageName());
        apkFileRecord.setAppVersion(NumberUtils.toInt(apkInfo.getVersionCode()));
        apkFileRecord.setAppVersionName(apkInfo.getVersionName());
        apkFileRecord.setCreatedBy(userId + "");
        apkFileRecord.setCreatedTime(DateUtil.getCurrentDate());

        apkFileRecordDao.add(apkFileRecord);

        //add app info
        AppInfo appInfo = new AppInfo();
        appInfo.setAppCode(appCode);
        appInfo.setCreatedTime(DateUtil.getCurrentDate());
        appInfo.setCreatedBy(userId + "");
        appInfo.setAppVersionName(apkFileRecord.getAppVersionName());
        appInfo.setAppVersion(apkFileRecord.getAppVersion());
        appInfo.setApkFileId(apkFileRecord.getId().toString());
        appInfo.setAppLogoPath(apkFileRecord.getAppLogoPath());
        appInfo.setAppName(apkFileRecord.getAppName());
        appInfo.setAppPackageName(apkFileRecord.getAppPackageName());
        appInfo.setAppPath(apkFileRecord.getAppPath());
        appInfo.setAppSize(appSize);
        appInfo.setVersion(0);
        appInfo.setAppInfoFlag(0);
        appInfo.setExpired(1);
        appInfo.setCompanyId(companyId);
        appInfoDao.add(appInfo);

        return apkFileRecord;
    }

    @Override
    public String addAppInfo(String deviceType, String developer, String summaryDesc, String osInfo, String detailDesc, String updateDesc, Integer apkFileId, String userId) throws SQLException {

        AppInfo appInfo = appInfoDao.getByApkFileId(apkFileId);
        if (appInfo == null) {
            throw new BaseAPIException(I18nUtil.getMessage(-1, null, "zh_CN"));
        }
        appInfo.setDetailDesc(detailDesc);
        appInfo.setDeveloper(developer);
        appInfo.setDeviceType(deviceType);
        appInfo.setOsInfo(osInfo);
        appInfo.setSummaryDesc(summaryDesc);
        appInfo.setUpdateDesc(updateDesc);
        appInfo.setUpdatedBy(userId);
        appInfo.setUpdatedTime(DateUtil.getCurrentDate());
        appInfo.setExpired(0);
        appInfoDao.update(appInfo);

        return "成功";
    }

    @Override
    public String setAppDownloadRule(String userId, String dvcRule, String appCode, String downloadTimeRule, String updateRule, String downloadRule, String downloadTimeStart, String downloadTimeEnd, String companyId, String recommendRule) throws SQLException {

        //首先通过app_code 查询 此 rule
        AppDownloadRule appDownloadRule = appDownloadRuleDao.getAppDownloadRuleByAppCode(appCode);
        //没有的话新增
        if (appDownloadRule == null) {
            appDownloadRule = new AppDownloadRule();
            appDownloadRule.setAppCode(appCode);
            appDownloadRule.setCompanyId(NumberUtils.toInt(companyId));
            appDownloadRule.setDownloadRule(NumberUtils.toInt(downloadRule));
            appDownloadRule.setDownloadTimeRule(NumberUtils.toInt(downloadTimeRule));
            if (!downloadTimeRule.equals("0")) {
                appDownloadRule.setDownloadTimeStart(downloadTimeStart);
                appDownloadRule.setDownloadTimeEnd(downloadTimeEnd);
            }
            appDownloadRule.setDvcRule(NumberUtils.toInt(dvcRule));
            appDownloadRule.setRecommendRule(recommendRule);
            appDownloadRule.setUpdateRule(NumberUtils.toInt(updateRule));

            appDownloadRuleDao.add(appDownloadRule);
        } else {
            appDownloadRule.setDownloadRule(NumberUtils.toInt(downloadRule));
            appDownloadRule.setDownloadTimeRule(NumberUtils.toInt(downloadTimeRule));
            if (!downloadTimeRule.equals("0")) {
                appDownloadRule.setDownloadTimeStart(downloadTimeStart);
                appDownloadRule.setDownloadTimeEnd(downloadTimeEnd);
            }
            appDownloadRule.setDvcRule(NumberUtils.toInt(dvcRule));
            appDownloadRule.setRecommendRule(recommendRule);
            appDownloadRule.setUpdateRule(NumberUtils.toInt(updateRule));

            appDownloadRuleDao.update(appDownloadRule);
        }

        return "成功";
    }

    @Override
    public Map<String ,Object>  apkListByWeb(String companyId, String index, String page, String appCode, String dvcType) {

        Map<String ,Object> map = new HashMap<String ,Object>();
        map.put("size",appInfoDao.apkListCount(companyId,appCode,dvcType));
        map.put("index",index);
        map.put("apkList",appInfoDao.getApkListByWeb(companyId,index,page,appCode,dvcType));

        return map;
    }

    @Override
    public String deleteApk(String apkId,String userId) throws SQLException {

        ApkFileRecord apkFileRecord = apkFileRecordDao.get(apkId);
        if(apkFileRecord == null){
            throw new BaseAPIException(I18nUtil.getMessage(-1, null, "zh_CN"));
        }
        //删除操作
        apkFileRecord.setIsDeleted(true);
        apkFileRecord.setUpdatedTime(DateUtil.getCurrentDate());
        apkFileRecord.setUpdatedBy(userId);
        apkFileRecordDao.update(apkFileRecord);
        return "删除成功";
    }


    private void checkTimeStamp(String timeStamp){
        long time = NumberUtils.toLong(timeStamp);
        long serverTime = DateUtil.getCurrentDate().getTime();
        long result = serverTime - time;
        logger.info("相差毫秒数 ：" +result);
        if(result > 120000){
            int errorCode = ExceptionCodeStatusEnum.ACCESS_DATA_EXPIRED_EXCEPTION.toInt();
            String errorMsg = I18nUtil.getMessage(errorCode,null,"zh_CN");
            throw new BaseAPIException(errorMsg,errorCode);
        }
    }
}
